package com.tiger.cloud.filter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.tiger.cloud.auth0.jwt.TokenGenerator;
import com.tiger.cloud.auth0.jwt.interfaces.Claim;
import com.tiger.cloud.util.CookieManager;
import com.tiger.cloud.util.MagicConstants;

public class CurrentUserJpushCodeArgumentResolver implements HandlerMethodArgumentResolver {

	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterAnnotation(CurrentUserJpushCode.class) != null;
	}

	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		String token = request.getHeader(MagicConstants.User_Token);
		if (StringUtils.isEmpty(token)) {
			token = request.getParameter(MagicConstants.User_Token);
		}
		if (StringUtils.isEmpty(token)) {
			token = new CookieManager(request, null).getCookie(MagicConstants.User_Token);
		}
		if(!StringUtils.isEmpty(token)){
			Map<String, Claim> datas = TokenGenerator.getClaims(token);
			String jpushCode = datas.get(MagicConstants.SESSION_USER_JPUSH_CODE).asString();
			return jpushCode;
		}
		return null;
	}

}